﻿'
' Boogaloo® - http://www.mindfly.com
' Copyright (c) 2008
' by Mindfly, Inc.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
' INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
' DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
' SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
' SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
' WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
' THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System.IO
Imports Boogaloo.Core.UI
Imports Boogaloo.Admin.UI.Controls
Imports Boogaloo.Core
Imports Boogaloo.Core.BLL


Namespace UI.Webpages

    Partial Public Class MasterPages
        Inherits BaseAdminPage

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            If Not Page.IsPostBack Then

                pnl_subdir.Visible = False
                pnl_addmaster.Visible = False
                hyp_cancelshow.Visible = False

                Dim dirs As String() = Groove.GetFullDirectoryTree(Server.MapPath(CoreSettings.GetSetting("SITE_MastersDirectory")))
                Dim dirName As String = String.Empty
                For Each dirName In dirs
                    ddl_dir.Items.Add(New ListItem(Groove.RewriteServerPathAsVirtualPath(dirName)))
                Next

                BindPage()
            End If

        End Sub


        Private Sub BindPage()

            rpt_files.Visible = True
            rpt_mastertemplates.Visible = True

            ' Delete directory visibility
            Dim dircount As Integer = Directory.GetDirectories(Server.MapPath("~" & ddl_dir.SelectedValue)).Count
            Dim filecount As Integer = Directory.GetFiles(Server.MapPath("~" & ddl_dir.SelectedValue)).Count
            If dircount = 0 And filecount = 0 Then
                dwiz_dir.Visible = True
                lbl_nodeletedir.Visible = False
            Else
                dwiz_dir.Visible = False
                lbl_nodeletedir.Visible = True
            End If

            Dim dirFiles As String() = Directory.GetFiles(Server.MapPath("~" & ddl_dir.SelectedValue), "*.master")
            Dim bindFiles As New ArrayList
            Dim mtDict As Dictionary(Of String, MasterTemplate) = MasterTemplate.GetMasterTemplatesDictionary(Groove.admin_root.root_id)

            Dim fn As String = String.Empty
            For Each fn In dirFiles
                If Not mtDict.ContainsKey(fn) Then bindFiles.Add(fn)
            Next

            rpt_files.DataSource = bindFiles
            rpt_files.DataBind()
            If rpt_files.Items.Count = 0 Then
                rpt_files.Visible = False
                lit_nofiles.Visible = True
            Else
                lit_nofiles.Visible = False
            End If

            rpt_mastertemplates.DataSource = Groove.admin_root.master_templates()
            rpt_mastertemplates.DataBind()

            If rpt_mastertemplates.Items.Count = 0 Then
                rpt_mastertemplates.Visible = False
                lit_nomasterpages.Visible = True
            Else
                lit_nomasterpages.Visible = False
            End If




        End Sub

        Private Sub HideAllPanels()

            pnl_addmaster.Visible = False
            pnl_subdir.Visible = False
            txt_subdir.Text = String.Empty

            lb_showaddmaster.Visible = True
            lb_showsubdir.Visible = True
            txt_newmasterpage.Text = String.Empty

            hyp_cancelshow.Visible = False

        End Sub

#Region "Link Button and DropDownList Handlers"

        Protected Sub lb_show_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_showsubdir.Click, lb_showaddmaster.Click

            hyp_cancelshow.Visible = True
            hyp_cancelshow.NavigateUrl = Request.Url.PathAndQuery

            Dim lb As LinkButton = CType(sender, LinkButton)
            If lb.CommandArgument.ToLower = "subdir" Then
                hyp_cancelshow.Text = "Cancel adding a subdirectory"
                pnl_subdir.Visible = True
                lb_showsubdir.Visible = False

                lb_showaddmaster.Visible = True
                pnl_addmaster.Visible = False
                txt_newmasterpage.Text = String.Empty

            ElseIf lb.CommandArgument.ToLower = "addmaster" Then

                hyp_cancelshow.Text = "Cancel adding a new MasterPage"

                pnl_subdir.Visible = False
                lb_showsubdir.Visible = True

                pnl_addmaster.Visible = True
                lb_showaddmaster.Visible = False

                txt_subdir.Text = String.Empty

            End If

        End Sub



        Protected Sub lb_associate_Click(ByVal sender As Object, ByVal e As EventArgs)

            If Page.IsValid Then
                Dim index As Integer = CType(CType(sender, LinkButton).CommandArgument, Integer)

                Dim filePath As String = String.Empty
                Dim name As String = String.Empty
                With rpt_files.Items(index)
                    filePath = String.Format("~{0}{1}", ddl_dir.SelectedValue, CType(.FindControl("lit_filename"), Literal).Text)
                    name = CType(.FindControl("txt_alias"), TextBox).Text
                End With
                Dim master_template_id As Integer = MasterTemplate.InsertMasterTemplate(name, filePath, Groove.admin_root.root_id)
            End If

  
            Groove.RefreshPage()

        End Sub


        ''' <summary>
        ''' Handles the directory drop down SelectedIndexChanged event
        ''' </summary>
        Protected Sub ddl_dir_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddl_dir.SelectedIndexChanged

            HideAllPanels()

            BindPage()

        End Sub

#End Region



#Region "Repeater ItemDataBound Handlers"



        Protected Sub rpt_files_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt_files.ItemDataBound

            Dim fileName As String = CType(e.Item.DataItem, String)

            If fileName IsNot Nothing Then
                Dim info As New FileInfo(fileName)

                Dim lit_filename As Literal = CType(e.Item.FindControl("lit_filename"), Literal)
                lit_filename.Text = info.Name

                Dim txt_alias As TextBox = CType(e.Item.FindControl("txt_alias"), TextBox)
                txt_alias.Text = info.Name

                Dim rfv_alias As RequiredFieldValidator = CType(e.Item.FindControl("rfv_alias"), RequiredFieldValidator)
                rfv_alias.ValidationGroup = info.Name

                Dim lb_associate As LinkButton = CType(e.Item.FindControl("lb_associate"), LinkButton)
                lb_associate.ValidationGroup = info.Name
                lb_associate.CommandArgument = e.Item.ItemIndex

            End If

        End Sub


        Protected Sub rpt_mastertemplates_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt_mastertemplates.ItemDataBound

            Dim mt As MasterTemplate = CType(e.Item.DataItem, MasterTemplate)

            If mt IsNot Nothing Then

                Dim validationgroup As String = String.Format("editalias{0}", e.Item.ItemIndex)

                Dim lht_alias As LabelHiddenTextbox = CType(e.Item.FindControl("lht_alias"), LabelHiddenTextbox)
                lht_alias.label = mt.name
                'spht_alias.label = "(Click to edit)"
                lht_alias.Text = mt.name
                lht_alias.CommandArgument = mt.master_template_id
                lht_alias.ValidationGroup = validationgroup

                Dim hyp As HyperLink = CType(e.Item.FindControl("hyp_master_virtual_path"), HyperLink)
                hyp.NavigateUrl = String.Format("{0}MasterPageEditor.aspx?master={1}", Groove.path_admin_host, mt.master_template_id.ToString)
                hyp.Text = mt.master_virtual_path

                Dim dwiz As CommitWizard = CType(e.Item.FindControl("dwiz"), CommitWizard)
                dwiz.CommandArgument = mt.master_template_id
                If mt.nodes.Count > 0 Then dwiz.Visible = False

            End If

        End Sub


#End Region



#Region "Custom Control Handlers"

        ''' <summary>
        ''' Creates new 'Masters' directory ... assumed to be used for new master pages
        ''' or
        ''' Creates a new MasterPage in the directory selected using CodeTemplate
        ''' </summary>
        Protected Sub cwiz_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cwiz_createdirectory.Click, cwiz_newmasterpage.Click

            If Page.IsValid Then

                Dim cwiz As CommitWizard = CType(sender, CommitWizard)

                If cwiz IsNot Nothing Then

                    If cwiz.CommandArgument.ToLower = "subdir" Then
                        Dim new_folder_name As String = Node.UrlRewriteVirtualPathEncoder(txt_subdir.Text).Replace("-", String.Empty)
                        Dim dirName As String = Server.MapPath("~" & ddl_dir.SelectedValue) & new_folder_name
                        
                        Directory.CreateDirectory(dirName)
                        Dim newFolder As String = ddl_dir.SelectedValue & new_folder_name & "/"
                        ddl_dir.Items.Add(New ListItem(newFolder))
                        ddl_dir.SelectedValue = newFolder





                    ElseIf cwiz.CommandArgument.ToLower = "masterpage" Then

                        Dim dirName As String = Server.MapPath("~" & ddl_dir.SelectedValue)
                        Dim filename As String = Node.UrlRewriteVirtualPathEncoder(txt_newmasterpage.Text)

                        If filename.ToLower.EndsWith("master") Then filename = filename.Substring(0, filename.ToLower.LastIndexOf("master") - 1)
                        filename &= ".master"

                        ' transfer contents of template code file to new file
                        Groove.WriteTextFileContents(dirName & filename, Groove.GetTextFileContents(String.Format("{0}/{1}.config", Server.MapPath(Groove.path_code_templates), cwiz.CommandArgument.ToLower)))

                    End If


                End If


                HideAllPanels()

                BindPage()
            End If

        End Sub


        Protected Sub dwiz_dir_Click(ByVal sender As Object, ByVal e As EventArgs) Handles dwiz_dir.Click

            If Page.IsValid Then

                Dim path As String = Server.MapPath("~" & ddl_dir.SelectedValue)
                If Directory.GetDirectories(path).Count = 0 And Directory.GetFiles(path).Count = 0 Then Directory.Delete(path)

                Groove.RefreshPage()

            End If

        End Sub

        ''' <summary>
        ''' Changes the alias of a master page.  The alias is simply a nicer way to refer to the master page.
        ''' </summary>
        Protected Sub lht_alias_Click(ByVal sender As Object, ByVal e As EventArgs)

            If Page.IsValid Then

                Dim lht As LabelHiddenTextbox = CType(sender, LabelHiddenTextbox)
                Dim master_template_id As Integer = CType(lht.CommandArgument, Integer)
                Dim mt As MasterTemplate = MasterTemplate.GetMasterTemplate(master_template_id)
                mt.name = lht.Text
                mt.Update()

                BindPage()

            End If

        End Sub


        ''' <summary>
        ''' Removes an association between a masterpage and thecurrent site
        ''' </summary>
        Protected Sub dwiz_Click(ByVal sender As Object, ByVal e As EventArgs)

            Dim dwiz As CommitWizard = CType(sender, CommitWizard)
            Dim master_template_id As Integer = CType(dwiz.CommandArgument, Integer)

            Dim success As Boolean = MasterTemplate.DeleteMasterTemplate(master_template_id)
            Response.Redirect(Request.Url.AbsoluteUri)

        End Sub


#End Region

    End Class

End Namespace